import { verifyUrl } from '@/utils/toolsValidate.ts'
import { nextTick } from 'vue'
import router from '@/router/index'
import { storeToRefs } from 'pinia'
import { useThemeStore } from '@/stores/themeStore'
import { i18n } from '@/i18n/index'
import { Local } from '@/utils/storage.ts'

/**
 * 打开外部链接
 * @param val 当前点击项菜单
 */
export function handleOpenLink(val: RouteItem) {
    const { origin, pathname } = window.location
    router.push(val.path)
    if (verifyUrl(<string>val.meta?.isLink)) window.open(val.meta?.isLink)
    else window.open(`${origin}${pathname}#${val.meta?.isLink}`)
}

/**
 * 设置浏览器标题国际化
 * @methods const title = useTitle; ===> title()
 */
export const useTitle = () => {
    const stores = useThemeStore()
    const { themeConfig } = storeToRefs(stores)
    nextTick(() => {
        let webTitle = ''
        const globalTitle: string = themeConfig.value.globalTitle
        const { path, meta } = router.currentRoute.value
        if (path === '/login') {
            webTitle = <string>meta.title
        } else {
            webTitle = setTagsViewNameI18n(router.currentRoute.value)
        }
        document.title = `${webTitle} - ${globalTitle}`
    })
}

/**
 * 设置 自定义 tagsView 名称、自定义 tagsViews 名称国际化
 * @param item 路由 query、params 中的 tagsViewName
 * @returns 返回当前 tagsViewName 名称
 */
export const setTagsViewNameI18n = (item: any) => {
    let tagsViewName: string = ''
    const { query, params } = item
    const pattern = /^\{("(zh-cn|en|zh-tw)":"[^,]+",?){1,3}}$/
    if (query?.tagsViewName || params?.tagsViewName) {
        if (pattern.test(query?.tagsViewName) || pattern.test(params?.tagsViewName)) {
            // 国际化
            const urlTagsParams =
                (query?.tagsViewName && JSON.parse(query?.tagsViewName)) || (params?.tagsViewName && JSON.parse(params?.tagsViewName))
            tagsViewName = urlTagsParams[i18n.global.locale.value]
        } else {
            // 非国际化
            tagsViewName = query?.tagsViewName || params?.tagsViewName
        }
    } else {
        // 非自定义 tagsView 名称
        // tagsViewName = i18n.global.t(meta.title);
    }
    return tagsViewName
}

/**
 * 全局组件大小
 * @returns 返回 `window.localStorage`中读取的缓存值 `globalComponentSize`
 */
export const globalComponentSize = (): string => {
    const stores = useThemeStore()
    const { themeConfig } = storeToRefs(stores)
    return Local.get('themeConfig')?.globalComponentSize || themeConfig.value?.globalComponentSize
}

/**
 * 图片懒加载
 * @param el dom 目标元素
 * @param arr data-xxx 属性用语存储页面或应用程序的私有自定义数据
 */
export const lazyImg = (el: string, arr: EmptyArrayType) => {
    const io = new IntersectionObserver((res) => {
        res.forEach((v: any) => {
            if (v.isIntersecting) {
                const { img, key } = v.target.dataset
                v.target.src = img
                v.target.onload = () => {
                    io.unobserve(v.target)
                    arr[key]['loading'] = false
                }
            }
        })
    })
    nextTick(() => {
        document.querySelectorAll(el).forEach((img) => io.observe(img))
    })
}

/**
 * 对象深克隆
 * @param obj 源对象
 * @returns 克隆后的对象
 */
export const deepClone = (obj: EmptyObjectType) => {
    let newObj: EmptyObjectType
    try {
        newObj = obj.push ? [] : {}
    } catch (error: any) {
        console.error(error)
        newObj = {}
    }
    for (const attr in obj) {
        if (obj[attr] && typeof obj[attr] == 'object') {
            newObj[attr] = deepClone([attr])
        } else {
            newObj[attr] = obj[attr]
        }
    }
    return newObj
}

/**
 * 判断是否为移动端
 */
export const isMobile = () => {
    if (
        navigator.userAgent.match(
            /('phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone')/i,
        )
    ) {
        return true
    } else {
        return false
    }
}

export const resetForm = (formData: any, defaultForm: any = {}) => {
    Object.keys(formData).forEach((key) => {
        formData[key as keyof typeof formData] = defaultForm[key as keyof typeof formData] || ''
    })
}
